package com.atguigu.eduservice.listener;

import com.alibaba.excel.context.AnalysisContext;
import com.alibaba.excel.event.AnalysisEventListener;
import com.atguigu.eduservice.entity.EduSubject;
import com.atguigu.eduservice.entity.excel.SubjectData;
import com.atguigu.eduservice.service.EduSubjectService;
import com.atguigu.servicebase.exceptionhandler.GuliException;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;

//监听器是自己创建对象，不是使用spring创建对象
public class SubjectListener extends AnalysisEventListener<SubjectData> {

    //想要获取其他的对象，手动注入对象，使用构造器注入对象,
    public EduSubjectService subjectService;

    public SubjectListener() {
    }
    public SubjectListener(EduSubjectService subjectService) {
        this.subjectService = subjectService;
    }
    //读取Excel表示一行行读取的，不包括表头
    @Override
    public void invoke(SubjectData data, AnalysisContext context) {
        //判断Excel表是否为null
        if (data==null){
            throw new GuliException(20001,"Excel表为null");
        }
        //判断一级分类是否重复,直接在数据库中查询是否有相同的name
        EduSubject oneSubject =this.existOneSubjectName(subjectService, data.getOneSubjectName());
        if (oneSubject==null){//说明没有相同的一级分类，可以进行添加
            oneSubject=new EduSubject();
            oneSubject.setTitle(data.getOneSubjectName());
            oneSubject.setParentId("0");//一级分类
            subjectService.save(oneSubject);
        }

        //判断二级分类是否重复
        //获取一级分类的id
        String pid=oneSubject.getId();
        EduSubject twoSubject = this.existTwoSubjectName(subjectService, data.getTwoSubjectName(), pid);
        if (twoSubject==null){
            twoSubject=new EduSubject();
            twoSubject.setTitle(data.getTwoSubjectName());
            twoSubject.setParentId(pid);//一级分类
            subjectService.save(twoSubject);
        }
    }

    //防止获取重复同样的信息
    //获取第一列的信息
    private EduSubject existOneSubjectName(EduSubjectService subjectService,String name){
        QueryWrapper<EduSubject> wrapper=new QueryWrapper<>();
        wrapper.eq("title",name)
                .eq("parent_id","0");
        EduSubject subject = subjectService.getOne(wrapper);
        return subject;
    }

    private EduSubject existTwoSubjectName(EduSubjectService subjectService,String name,String pid){
        QueryWrapper<EduSubject> wrapper=new QueryWrapper<>();
        wrapper.eq("title",name)
                .eq("parent_id",pid);
        EduSubject subject = subjectService.getOne(wrapper);
        return subject;
    }
    @Override
    public void doAfterAllAnalysed(AnalysisContext context) {

    }
}
